<?php

namespace app\api\controller;

use think\Controller;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class Upload extends Controller
{
    public function __construct()
    {
        if (!session('admin_user.adminid')) {
            $result = [
                'error' => 1,
                'message' => '未登录'
            ];

            return json($result);
        }
    }

    /**
     * 通用图片上传接口
     * @return \think\response\Json
     */
    public function uploadImage()
    {
        $config = [
            'size' => 2097152,
            'ext' => 'jpg,gif,png,bmp,js'
        ];
        $file = request()->file('file');
        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads/image');
        $save_path = '/uploads/image';
        $info = $file->validate($config)->move($upload_path);
        if ($info) {
            $result = [
                'success' => 1,
                'url' => str_replace('\\', '/', $save_path . $info->getSaveName())
            ];
        } else {
            $result = [
                'error' => $file->getError()
            ];
        }
        return json($result);
    }

    /**
     * 通用图片上传接口
     * @return \think\response\Json
     */
    public function uploadFile()
    {
        $config = [
            'size' => 10485760,//10M
            'ext' => 'xlsx'
        ];
        $file = request()->file('file');
        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/public/uploads/file');
        $save_path = '/public/uploads/file/';
        $info = $file->validate($config)->move($upload_path);
        if ($info) {
            $result = [
                'success' => 0,
                'url' => str_replace('\\', '/', $save_path . $info->getSaveName())
            ];
        } else {
            $result = [
                'error' => $file->getError()
            ];
        }
        return json($result);
    }
}